<?php
namespace submodule\base;

use Yii;
use base\YiiMobo;


/**
 * Site controller
 */
class BaseSubmoduleApiController extends \submodule\base\BaseSubmoduleController
	
   {
	public $enableCsrfValidation = false;
	   
    public $defaultRoute = 'index';
	

	public $ino;

    public function init(){
	    parent::init();

		
		$this->submodel = (object)null;
		$this->submodel->default_field = [];
		
		$this->moduleid = isset($this->moduleid) ? $this->moduleid : $this->module->id;
		$this->submodel->modelid = isset($this->submodel->modelid) ? $this->submodel->modelid : self::getModelid();
		//$this->submodel->modelid = $this->submodel->modelid ? $this->submodel->modelid : self::getModelid();
		if (!$this->submodel->modelid){
		    exit('not found this default model');
			
		}
		//exit($this->submodel->modelid);
		$this->submodel->models = Yii::$app->FileCache->get('submodule_model_'.$this->submodel->modelid);


		$this->submodel->fields = $this->submodel->models['fields'];
		$this->submodel->primarykey =  $this->submodel->models['primarykey'];

		$this->submodel->tablename = '{{%'.$this->submodel->models['models']['tablename'].'}}';
		
		$this->submodel->data_tablename = isset($this->submodel->models['models']['data_tablename']) ? $this->submodel->models['models']['data_tablename'] : '{{%'.$this->submodel->models['models']['tablename'].'_data}}';


        

	}

	/**
	*  获取modelid
	*/
	public function getModelid(){
		$modelid = 0;
		$models = Yii::$app->FileCache->get('submodule_model');
		if ($models) foreach($models as $k=>$v){
			if (($this->moduleid == $v['tablename'] && $v['isdefault'] == 1) || $this->moduleid == $v['tablename']){
				$modelid = $v['modelid'];
				break;
			}
		}
		return $modelid;
	}
	
	
	public function getValue($data){
		if (method_exists($function, $field.'_index')){
			$viewfunction = $field.'_index';
			$v[$field] = $function->$viewfunction($fields[$field], $field, $value);
		}
	}
	

	/**
	*  检查接口状态是否开启
	*/
	public function checkApi($action, $return = false){
		
		if (!isset($this->submodel->models['models']['api'][$action]) || !$this->submodel->models['models']['api'][$action]['enable']) {
			$data = ['msg'=> '接口未开启', 'code'=> 423];
			if($return){
				return $data;
			}else{
				self::echojson($data);
			}
		}else{
			
			
		}
		
	}
	/**
	*  列表页接口
	*/
	public function apiList($return = false){
		$this->requests = $_GET;
		$this->checkApi('list', $return);
		
		$bindparam = [];
		$search = isset($this->requests['search']) ? $this->requests['search'] : NULL;
		
		$apiFields = $this->submodel->models['models']['api']['list']['fields'];
		$condition = isset($this->requests['condition']) ? $this->requests['condition'] : NULL;
		$getFields = $this->sqlFields('list');
		$fields = $getFields['fields'];
		$sql = $getFields['sql'];
		$sql .= in_array('status', array_keys($fields)) ? ' where a.`status` = 1': ' where 1 = 1';

		//按条件查询
		if($condition) foreach($condition as $field=>$value){
			if(in_array($field, $apiFields) && $value != ''){
				$fieldname = ($fields[$field]['primarytable'] ? 'a' : 'b').'.`'.$field.'`';
				$sql .= " and $fieldname = :condition_$field";
				$bindparam['condition_'.$field] = $value;
			}
		}
		//搜索字段
		if (isset($search['keyword'])){
			foreach($modelsFields as $v){
				if (isset($v['setting']['search']) && $v['setting']['search']){
					$field = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';
					$sql .= " and $field like '%".$search['keyword']."%'";
				}
			}
		}
		if (isset($search['starttime'])){
			 $sql .= " and a.`addtime` >= :starttime";
			 $bindparam['starttime'] = strtotime($search['starttime']) ? strtotime($search['starttime']) : $search['endtime'];
		}
		if (isset($search['endtime'])){
			 $sql .= " and a.`addtime` <= :endtime";
			 $bindparam['endtime'] = strtotime($search['endtime']) ? strtotime($search['endtime']) : $search['endtime'];
		}

		
		$orderby = isset($this->requests['orderby']) ? $this->requests['orderby'] : "a.`{$this->submodel->primarykey}` desc";
		$orderby = ' order by '.$orderby;
		//exit($sql);
		$data = $this->queryPages($sql, $bindparam, $orderby, false);
		
		$class = $this->loadSubmoduleExtend('Api', $this->submodel->tablename, $this->submodel->models, [], $this->modelid, $this->action->id);
		foreach($data['results'] as $k=>$v){
			
			foreach($v as $field=>$value){
				$function = $field.'List';
				if (method_exists($class, $function)){
					$v[$field] = $class->$function($fields[$field]['fieldid'], $field, $v);
				}
			}
			
			$data['results'][$k] = $v;
		}

		if($return){
			return $data;
		}else{
			self::echojson($data);
		}
	}
	
	/**
	*  详情页接口
	*/
	public function apiView($return = false){
		$this->requests = $_GET;
		$this->checkApi('view', $return);
		$this->isRequired([$this->submodel->primarykey]);
		$bindparam = [':postid'=> $this->requests[$this->submodel->primarykey]];
		
		$getFields = $this->sqlFields('list');
		$fields = $getFields['fields'];
		$sql = $getFields['sql'];
		$sql .= " where a.`{$this->submodel->primarykey}` = :{$this->submodel->primarykey}";
		$sql .= in_array('status', array_keys($fields)) ? ' and a.`status` = 1': '';
		$data = $this->queryPages($sql, $bindparam, '', false);
		

		$class = $this->loadSubmoduleExtend('Api', $this->submodel->tablename, $this->submodel->models, [], $this->modelid, $this->action->id);
		foreach($data['results'] as $k=>$v){
			foreach($v as $field=>$value){
				$viewfunction = $field.'View';
				if (method_exists($class, $viewfunction)){
					$v[$field] = $function->$viewfunction($fields[$field]['fieldid'], $field, $value);
				}
			}
			
			$data['results'][$k] = $v;
		}
        $function = 'viewCallback';
		if (method_exists($class, $function)){
			$class->$function('', '', $this->requests);
		}
		if($return){
			return $data;
		}else{
			self::echojson($data);
		}
		
	}
	
	/**
	*  添加内容接口
	*/
	public function apiCreate($return = false){
		header("Access-Control-Allow-Origin:*");
		$this->requests = $_POST;
		
		$this->checkApi('create', $return);
		self::apiSave('Create', $return);
		
	}
	/**
	*  修改内容接口
	*/
	public function apiUpdate($return = false){
		header("Access-Control-Allow-Origin:*");
		$this->requests = $_POST;
		$this->checkApi('update', $return);
		self::apiSave('Update', $return);
		
	}
	
	
	/**
	 * 保存表单提交数据
     * 
	 */
	public function apiSave($action = 'Create'){
		
		$this->isRequired($this->apiFields(strtolower($action), 'required'));
		$id = isset($this->requests[$this->submodel->primarykey]) ? $this->requests[$this->submodel->primarykey] : NULL;
		$class = $this->loadSubmoduleExtend('Api', $this->submodel->tablename, $this->submodel->models, $this->requests, $this->modelid, $this->action->id);
		
		$data = [];
		$data_data = [];
		$fields = [];
		$dataTableName = false; 
		//print_r($this->requests);exit;
	    $apiFields = $this->apiFields(strtolower($action));
		foreach($this->submodel->models['fields'] as $k=>$v){
			//if (!in_array($v['field'], $apiFields)) continue;
			$fields[] = $v['field'];
			if ($v['field'] != $this->submodel->primarykey){
				$defaultvalue = isset($v['setting']['defaultvalue']) ? $v['setting']['defaultvalue'] : (in_array($v['fieldtype'], ['int', 'tinyint', 'smallint', 'mediumint', 'integer']) ? 0 : NULL);
				if (!in_array($v['field'], $apiFields)){
                    $value = $defaultvalue;
					if ($action == 'Update') continue;
				}else{
				    $value = isset($this->requests[$v['field']]) ? $this->requests[$v['field']] : $defaultvalue;
			    }
				if ($v['formtype'] == 'checkbox'){
					$value = $value ? join(',',$value) : '';
				}
			    if (in_array($v['formtype'], ['image', 'images'])){
					if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result)){
						$upload_config = array(
							"savePath" => "../uploads/".$this->submodel->models['models']['type'],
							"thumbWidth" => isset($v['param']['thumb_width']) ? $v['param']['thumb_width'] : 800,
						);
						$Uploader = new \common\components\Uploader($v['field'], $upload_config, 'base64');
						$info = $Uploader->getFileInfo();
						$value = $info['state'] == "SUCCESS" ? ltrim($info['url'], "\.\./") : '';
					}
				}
				if (method_exists($class, $v['field'].$action)){
					$classfunction = $v['field'].$action;
					$value = $class->$classfunction($v['fieldid'], $v['field']);
				}
				if($v['primarytable']){
                    $data[$v['field']] = $value;
				}else{
					$dataTableName = '{{%{$this->submodel->tablename}_data}}';
					$data_data[$v['field']] = $value;
				}
			}
		}
		if (in_array('updatetime', $fields)) $data['updatetime'] = time(); 
		if ($action == 'Create'){
			if (in_array('addtime', $fields)) $data['addtime'] = time(); 
		}else{
            if (in_array('addtime', $fields)) unset($data['addtime']);
		}
		$connection = Yii::$app->db;
        $connection->open();
		//print_r($data);exit;
		
		//update
		if ($action == 'Update'){
			$insertid = $id;
			try{
				$results = $connection->createCommand()->update($this->submodel->tablename, $data, $this->submodel->primarykey.' = '.$id)->execute();
				if($dataTableName){
					$results = $connection->createCommand()->update($dataTableName, $data_data, $this->submodel->primarykey.' = '.$id)->execute();
				}
				$function = 'updateCallback';
				if (method_exists($class, $function)){
					$class->$function('', '', $this->requests);
				}
				self::echojson(['result'=>1, $this->submodel->primarykey => $insertid]);
		    }catch (Exception $e){
				self::errmsg('db error '.$e->getMessage());
		    }
		//insert
		}else{
			try{
				$connection->createCommand()->insert($this->submodel->tablename, $data)->execute();
				$results = $insertid = $data_data[$this->submodel->primarykey] = $connection->getLastInsertID();
				if($dataTableName){
					$results = $connection->createCommand()->insert($dataTableName, $data_data)->execute();
				}
				$function = 'createCallback';
				if (method_exists($class, $function)){
					$class->$function('', '', $this->requests);
				}
				self::echojson(['result'=>1, $this->submodel->primarykey => $insertid]);
			}catch (Exception $e){
				self::errmsg('db error '.$e->getMessage());
		    }
		}

	}
	/**
	*  接口显示或者接收的字段
	*/
	public function sqlFields($action){
		$fields = [];
		$jointable = [];
		$onfield = [];
		$apiFields = $this->submodel->models['models']['api'][$action]['fields'];
		$modelsFields = $this->submodel->models['fields'];
		$fields['*'] = ["a.`{$this->submodel->primarykey}`"];
		foreach($modelsFields as $k=>$v){
			if (in_array($v['field'], $apiFields) && $v['primarytable'] != 2){
				$fields['*'][] = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';  
			}
			$fields[$v['field']] = ['fieldid'=> $k, 'primarytable'=> $v['primarytable']]; 
		}
		foreach($fields as $k=>$v){
			if ($k == '*') continue;
			$joinfield = $this->submodel->models['models']['api']['list']['joinwith'][$k]['joinfield'];
			$table = $this->submodel->models['models']['api']['list']['joinwith'][$k]['table'];
			$field = $this->submodel->models['models']['api']['list']['joinwith'][$k]['field'];
			if ($joinfield && $field && $table){
				foreach(explode(',', $field) as $fd){
				   $fields['*'][] = "$table.`$fd`";
				}
				$jointable[] = " inner join $table on a.`$k` = $table.`$joinfield`";
			}
		}
		$fields['*'] = join(', ',$fields['*']);

		$sql = "SELECT {$fields['*']} FROM {$this->submodel->tablename} a";
		
		if (strpos($fields['*'],'b.`')){
			$sql .= " inner join {{%{$this->submodel->tablename}_data}} b on a.`{$this->submodel->primarykey}` = b.`{$this->submodel->primarykey}`";
		}
		foreach($jointable as $tb){
			$sql .= $tb; 
		}
		
		return ['fields'=> $fields, 'jointable'=> $jointable, 'sql'=> $sql];
	}
	
	public function apiFields($action, $type = 'fields'){
		$fields = @$this->submodel->models['models']['api'][$action][$type];
		return $fields ? $fields : [];
	}

}
